#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QStyle>
#include <QScreen>
#include <QApplication>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "../../thread/ReceiveThread.h"
#include "../main/mainwindow.h"
#include "User.h"

extern User user;
extern ReceiveThread* recvThread;
extern MainWindow* mainWindow;

LoginWindow::LoginWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
    dbHandler = new DbHandler(this);
    
    // 设置窗口居中
    setGeometry(
        QStyle::alignedRect(
            Qt::LeftToRight,
            Qt::AlignCenter,
            size(),
            QApplication::primaryScreen()->availableGeometry()
        )
    );
    
    // 设置回车键登录
    connect(ui->lineEdit_username, &QLineEdit::returnPressed, this, &LoginWindow::on_pushButton_login_clicked);
    connect(ui->lineEdit_password, &QLineEdit::returnPressed, this, &LoginWindow::on_pushButton_login_clicked);

    connect(recvThread, &ReceiveThread::recvDbStatus, this, &LoginWindow::recvDbStatus);
    
    // 清除状态信息
    clearStatus();
}

LoginWindow::~LoginWindow()
{
    delete ui;
}

void LoginWindow::recvDbStatus(const QByteArray& status, const quint16& userId, const QByteArray& username, const quint16& userType) {
    if (status == "SUCCESS_LOGIN") {
        user = User(userId, username, userType);
        showStatus("登录成功！", false);
        openMainWindow();
    } else if (status == "NO_USER") {
        showStatus("用户名不存在");
    } else if (status == "WRONG_PASS") {
        showStatus("密码错误");
    } else if (status == "ERROR") {
        showStatus("数据库错误");
    }
}

void LoginWindow::showEvent(QShowEvent *event)
{
    setGeometry(
        QStyle::alignedRect(
            Qt::LeftToRight,
            Qt::AlignCenter,
            size(),
            QApplication::primaryScreen()->availableGeometry()
        )
    );
    QWidget::showEvent(event);
}

void LoginWindow::on_pushButton_login_clicked()
{
    if (!validateInput()) {
        return;
    }
    
    QString phone = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    
    showStatus("正在登录...", false);
    dbHandler->tryLogin(phone, password);
}

void LoginWindow::on_pushButton_register_clicked() {
    this->hide();
    registerWindow = std::make_unique<RegisterWindow>(dbHandler);
    connect(registerWindow.get(), &RegisterWindow::backToLogin, [this]() {
        registerWindow.reset();
        this->show();
    });
    registerWindow->show();
}

void LoginWindow::showStatus(const QString &message, bool isError)
{
    ui->label_status->setText(message);
    if (isError) {
        ui->label_status->setStyleSheet("color: red; font-size: 12px;");
    } else {
        ui->label_status->setStyleSheet("color: blue; font-size: 12px;");
    }
}

void LoginWindow::openMainWindow() {
    mainWindow = new MainWindow();
    this->hide();
    mainWindow->show();
}

void LoginWindow::clearStatus()
{
    ui->label_status->setText("");
}

bool LoginWindow::validateInput()
{
    QString username = ui->lineEdit_username->text().trimmed();
    QString password = ui->lineEdit_password->text();
    
    if (username.isEmpty()) {
        showStatus("请输入用户名");
        ui->lineEdit_username->setFocus();
        return false;
    }
    
    if (password.isEmpty()) {
        showStatus("请输入密码");
        ui->lineEdit_password->setFocus();
        return false;
    }
    
    if (username.length() < 1) {
        showStatus("用户名至少需要1个字符");
        ui->lineEdit_username->setFocus();
        return false;
    }
    
    if (password.length() < 1) {
        showStatus("密码至少需要1个字符");
        ui->lineEdit_password->setFocus();
        return false;
    }
    
    return true;
}